package com.spr.gw.controller.admin;

import com.spr.gw.common.ResultBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UploadController {

    @Value("${my.cfg.uploadPath}")
    private String uploadPath;

    @RequestMapping("uploadFile")
    public ResultBean uploadImg(@RequestParam(value = "file",required = false) MultipartFile file) {
        String fileName= file.getOriginalFilename();
        String fileType= fileName.substring(fileName.indexOf("."), fileName.length());
        String newFileName = System.currentTimeMillis() + fileType;
        String filePath = uploadPath + LocalDate.now() + "/";
        try {
            uploadFile(file.getBytes(), filePath, newFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map map = new HashMap<String, String>();
        map.put("src", "/" + filePath + newFileName);
        //返回json
        return ResultBean.createBySuccessMessage("上传成功",map);
    }

    @RequestMapping("/kind/uploadFile")
    public Map kindUploadImg(@RequestParam(value = "imgFile",required = false) MultipartFile file,
                             HttpServletRequest request) throws IOException {

        Map map = new HashMap<String, String>();
        String fileName= file.getOriginalFilename();
        String fileType= fileName.substring(fileName.indexOf("."), fileName.length());
        String newFileName = System.currentTimeMillis() + fileType;
        String filePath = uploadPath + LocalDate.now() + "/";
        try {
            uploadFile(file.getBytes(), filePath, newFileName);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("error", 1);
            map.put("msg", "upload file error");
            return map;
        }
        map.put("error", 0);
        map.put("url", "/" + filePath + newFileName);
        return map;
    }

    private void uploadFile(byte[] file, String filePath, String fileName) throws IOException {
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }
}
